package club.cearnach.web.controller.admin;

import club.cearnach.api.dto.NewsDTO;
import club.cearnach.entity.News;
import club.cearnach.api.exception.MovieNewsException;
import club.cearnach.api.exception.MoviePathException;
import club.cearnach.api.form.PageBean;
import club.cearnach.api.service.INewsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.io.IOException;

/**
 * @author 阮胜
 * @date 2018/5/20 12:51
 */
@Api(tags = "后台新闻控制类")
@Controller
@RequestMapping("/admin/movie/news")
@Slf4j
public class BackgroundNewsController {
    private final INewsService newsService;

    public BackgroundNewsController(INewsService newsService) {
        this.newsService = newsService;
    }

    @GetMapping("/list")
    public String list(PageBean pageBean, Model model) {
        Page<News> movieNewsPage = newsService.findAllOrderByCreateDateDesc(pageBean);
        model.addAttribute(movieNewsPage.getContent());
        model.addAttribute("totalPage", movieNewsPage.getTotalPages());
        model.addAttribute("currentPage", pageBean.getPage());
        return "admin/movie-news-list";
    }

    @PostMapping("/save")
    @ResponseBody
    public boolean save(NewsDTO newsDTO) throws IOException, MoviePathException {
        newsService.save(newsDTO);
        return true;
    }

    @GetMapping("/edit/form/{id}")
    public String editForm(@PathVariable("id") @Min(1) Integer id, Model model) throws MovieNewsException {
        News news = newsService.findById(id);
        model.addAttribute(news);
        return "admin/movie-news-save";
    }

    @ApiOperation("删除新闻")
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public boolean delete(@PathVariable("id") Integer id) throws MovieNewsException {
        newsService.delete(id);
        return true;
    }

    @ApiOperation("批量删除")
    @DeleteMapping("/delete/all")
    @ResponseBody
    public long deleteAll(@RequestParam(value = "id") Integer[] idArr) {
        return newsService.deleteIn(idArr);
    }


}
